define(function(require, exports){
	var $ = require('jquery');
	var pubjs = require('pubjs');
	var highGrid  = require('@base/highGrid');
	var baseGrid = require('@base/grid');
	var util = require('util');

	// 渲染条件
	function _renderConditions(i, val, data){
		var con = $('<div class="text-truncate renderCondition"/>').width(480);
		var dimType = data.DimType || (data.Name == LANG('活动') ? 1 : 2);
		var smartMonitorMetric = pubjs.config('smartMonitorMetric')[dimType];
		var smartMonitorOperator = pubjs.config('smartMonitorOperator');
		var text = [];

		var conditions = util.isArray(val) ? val : val.Conditions;

		util.each(conditions, function(item, idx){
			if(item){
				var value = +item.Value;
				// %为单位的，需要转换
				if(util.find(smartMonitorMetric,item.Name,'_id').NeedTrans){
					value = value*100;
				}
				text.push([item.IsAll ? LANG('最近30天') : LANG('当日')]);
				text.push(util.find(smartMonitorMetric,item.Name,'_id').Name);
				text.push(util.find(smartMonitorOperator,item.Comparison,'_id').Name);
				text.push(value);
				text.push(util.find(smartMonitorMetric,item.Name,'_id').Unit);
				text.push(idx == val.length-1 ? '' : '<span class="uk-text-muted">'+LANG('且')+'</span>');
			}
		});
		return con.attr('title', text.join(' ').replace(/<\/?[^>]*>/g,'')).html(text.join(' '));
	}

	// 渲染全内容
	function _renderConditionsContent(i, val, data, con){
		var html = $('<div class="text-truncate"/>').width(con.width);
		var title = '';

		if(util.isArray(val) && val.length){
			util.each(val, function(item, idx){
				if(item){
					var renderData = {
						'DimType': data.DimType,
						'Conditions': item
					}
					var text = _renderConditions(idx, item, renderData).text();

					// 组件title和text
					if(idx > 0){
						html.append(LANG('（或）'));
						title += '\r' + LANG('（或）') + '\r';
					}
					title += text;
					html.append(text);
				}
			});
		}
		// var icon = $('<i class="icon-view-content fr"/>').appendTo(html);
		if(util.isMobile()){
			html.click(function(ev){
				alert(title);
			});
		}
		return html.attr('title', title);
	}

	//渲染创建时间
	function _renderCreateTime(i, val, data, con){
		return util.date('Y-m-d', data.CreateTime);
	}

	// 渲染名字
	function _renderName(i, val, data, con){
		var icon = [
			null,
			['running', LANG('已开启')],
			['pause', LANG('已暂停')],
			['store', LANG('已归档')]
		]
		var status = icon[data.Status] || {};
		if(data.IsDeleted){
			status = icon[3];
		}
		var name = '';
		if(data.IsGranted || data.ReadOnly){
			name = $('<span/>');
		}else{
			name = $('<a/>');
		}
		name.attr({
			'target': '_self',
			'href': '#admin/smartMonitor/edit/' + data._id
		}).text(val).css({
			'vertical-align': 'middle'
		});

		var html = $([
			'<div class="text-truncate tl fl mr10" title="'+ val +'">',
				'<i title="'+status[1]+'" class="'+status[0]+' mr5"></i>',
			'</div>'
			].join('')).width(con.width-20).append(name);
		return html;
	}

	// 监控列表
	var MonitorList = highGrid.base.extend({
		init: function(config){
			config = pubjs.conf(0, config, {
					'url': 'monitor/listAlarms',
					'reqType': 'websocket',
					'cols': [
						{name: '_id', text: LANG('ID'), sort: false, width: 60, align: 'center'},
						{name:'Name', text:LANG('监控名称'), type:'index', width: 150, render:"reanderName",align:'left'},
						{name:'DimType', text:LANG('类型'), width: 60, render:"reanderDimType",align:'center'},
						{name:'Conditions', text:LANG('内容'),width: 400, render:'renderConditions', align: 'left'}
					],
					'metrics':[
						{name:'Method', text:LANG('监控操作'),render: 'renderMethod', align: 'left'},
						{name:'CreateTime', text:LANG('创建时间'),render: 'renderCreateTime', align: 'center'},
						{name:'AdvertiserId', text:LANG('广告主'),width: 250,render: 'renderAders', align: 'left'},
						// {name:'Remarks', text:LANG('备注'), render:'renderRemarks', align: 'left'}
					],
					param: {
						'order': 'CreateTime|-1'
					},
					'hasSelect': true,
					'hasTab': false,
					'hasSwitch': false,
					'hasAmount': false,
					'hasSearch': true,
					'hasExport': false,
					'hasRefresh': true,
					'hasWordsSearch': false,
					'hasMenu': true,
					'isSendMetrics': false,
					'gridName': 'smartMonitor'
				}
			);

			this.Super('init', arguments);
		},
		reanderName: function(i, val, data, con){
			return _renderName(i, val, data, con);
		},
		renderConditions: function(i, val, data, con){
			return _renderConditionsContent(i, val, data, con);
		},
		reanderDimType: function(i, val, data, con){
			return val == 1 ? LANG('推广组') : LANG('广告位');
		},
		renderRemarks: function(i, val, data, con){
			return $('<div class=""/>').text(val).attr('title',val);
		},
		renderCreateTime: function(i, val, data, con){
			return _renderCreateTime(i, val, data, con);
		},
		renderAders: function(i, val, data, con){
			var Aders = [];
			util.each(data.AdvertiserId,function(item){
				Aders.push(item.name);
			});
			if(Aders.length !== 0){
				return '<div class = "text-truncate">' + Aders.join('，') + '</div>';
			}
			return Aders;
		},
		renderMethod: function(i, val, data, con){
			var method = [];
			if(data.EnableNotice){
				method.push("发系统消息");
			}
			if(data.EnableEmail){
				method.push("发邮件提醒");
			}
			if(data.StopCampaign){
				method.push("暂停推广组");
			}
			return '<div class = "text-truncate">' + method.join(' ,') + '</div>';
		}
	});
	exports.monitorList = MonitorList;

	// 编辑时的条件列表
	var EditList = baseGrid.baseNoDate.extend({
		init : function(config){
			config = pubjs.conf( config, {
				"cols" : [
					{ type: 'id', width: 50 },
					{ name : "DimType", width: 80, text : LANG("维度"), align : "center", render: 'renderDimType' },
					{ name : "Conditions", width: 500 ,text : LANG("监控设置"), align : "left", render: 'renderCondition' }

				],
				'default_sort': false,
				"hasExport" : false,
				"hasAmount" : false,
				"hasTab" : false,
				'hasPager': false,
				'hasSelect': false,
				'hasSearch': false,
				'sub_field': '_id',
				'list': {
					'scroll_type': 'row',
					'scroll_size': 10
				}
			});

			this.Super( "init", arguments );
		},
		renderCondition: function(i, val, data){
			return _renderConditions(i, val, data);
		},
		renderDimType: function(i, val, data){
			return [null, LANG('活动'), LANG('广告位')][val];
		}
	});
	exports.editList = EditList;

	// 活动监控列表
	var CampaginMonitorList = baseGrid.baseNoDate.extend({
		init : function(config){
			config = pubjs.conf( config, {
				'url': 'monitor/listAlarms',
				'reqType': 'websocket',
				'cols': [
					{name: '_id', text: LANG('ID'), sort: false, width: 60, align: 'center'},
					{name:'Name', text:LANG('监控名称'), type:'index', width: 220, render:"reanderName",align:'left'},
					{name:'DimType', text:LANG('类型'), width: 50, render:"reanderDimType",align:'left'},
					{name:'Conditions', text:LANG('内容'), render:'renderConditions', align: 'left',width:350},
					{name:'Remarks', text:LANG('备注'), render:'renderRemarks', align: 'left'}
				],
				param: {
					'order': 'CreateTime|-1'
				},
				'sort': 'CreateTime',
				'hasTab': false,
				'hasSwitch': false,
				'hasAmount': false,
				'hasSearch': true,
				'hasExport': false,
				'hasRefresh': true,
				'hasSelect': true,
				'layout': {
					"rows":['search(.pb10)(auto)|filter(.h30 lh30 ml20)(auto)']
				},
				'list':{
					'rowSelect': true,
					'scroll_type': 'row',
					'scroll_size': 5
				}
			});

			this.Super( "init", arguments );
		},
		reanderName: function(i, val, data, con){
			data.ReadOnly = true;
			var html = _renderName(i, val, data, con);
			return html;
		},
		renderConditions: function(i, val, data, con){
			return _renderConditionsContent(i, val, data, con);
		},
		reanderDimType: function(i, val, data, con){
			var text = val == 1 ? LANG('活动') : LANG('广告位');
			return $('<div class="text-truncate"/>').text(text).attr('title',val).width(50);
		},
		renderRemarks: function(i, val, data, con){
			return $('<div class="text-truncate"/>').text(val).attr('title',val).width(180);
		}
	});
	exports.campaginMonitorList = CampaginMonitorList;

});